from pmapi import log
from pmapi import git
from pmapi import lock
from pmapi import utils
import os
import sys
import signal

PACKAGE_PATH = f"{utils.find_disk()}\\" + \
    "PEinjector\\package".replace('\\', os.sep)

exit_flag = False


def read_exit(*args, **kwargs):
    global exit_flag
    sys.stdout.write("\nPressed Ctrl+C, Will Exit...\n\n")
    exit_flag = True


def upgrade(pkg_name: list[str] | str | None = None, progress_callback=lambda **kwargs: None, progress_callback_args: dict = {}):
    global exit_flag
    lockn = lock.Lock("upgrade")
    if pkg_name is None:
        log.info("upgrade all packages")
        pkg_lists = os.listdir(PACKAGE_PATH)
    elif type(pkg_name) == str:
        log.info(f"upgrade package \"{pkg_name}\"")
        pkg_lists = [pkg_name]
    else:
        log.info("upgrade packages")
        pkg_lists = pkg_name
    signal.signal(signal.SIGINT, read_exit)
    for i in pkg_lists:
        if not os.path.exists(PACKAGE_PATH+os.sep+i):
            log.warn(f"package \"{i}\" not found")
            continue
        git.pull(PACKAGE_PATH+os.sep+i, depth=1,
                 progress_callback=progress_callback, progress_callback_args=progress_callback_args)
        if exit_flag:
            sys.stdout.write("Exit!")
            lockn.remove()
            return -1
    lockn.remove()
